import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as visitPlanApi from '@/api/visitPlan'
import type { VisitPlan } from '@/api/visitPlan'

// 定义走访相关的store
export const useVisitStore = defineStore('visit', () => {
  // 状态
  const visitPlans = ref<VisitPlan[]>([])
  const currentPlan = ref<VisitPlan | null>(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取走访计划列表
  const fetchVisitPlans = async (params?: {
    page?: number
    pageSize?: number
    status?: string
    keyword?: string
    dateRange?: string[]
  }) => {
    loading.value = true
    try {
      const res = await visitPlanApi.getVisitPlanList(params)
      visitPlans.value = res.data
      total.value = res.total
    } catch (error) {
      console.error('获取走访计划列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取走访计划详情
  const fetchVisitPlanDetail = async (id: string) => {
    loading.value = true
    try {
      const res = await visitPlanApi.getVisitPlanDetail(id)
      currentPlan.value = res
    } catch (error) {
      console.error('获取走访计划详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 创建走访计划
  const createVisitPlan = async (data: VisitPlan) => {
    loading.value = true
    try {
      const res = await visitPlanApi.createVisitPlan(data)
      // 创建成功后更新列表
      await fetchVisitPlans()
      return res
    } catch (error) {
      console.error('创建走访计划失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新走访计划
  const updateVisitPlan = async (id: string, data: Partial<VisitPlan>) => {
    loading.value = true
    try {
      const res = await visitPlanApi.updateVisitPlan(id, data)
      // 更新成功后更新列表
      await fetchVisitPlans()
      return res
    } catch (error) {
      console.error('更新走访计划失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 批量创建走访计划
  const batchCreateVisitPlans = async (data: VisitPlan[]) => {
    loading.value = true
    try {
      const res = await visitPlanApi.batchCreateVisitPlans(data)
      // 创建成功后更新列表
      await fetchVisitPlans()
      return res
    } catch (error) {
      console.error('批量创建走访计划失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 计算属性：获取今日走访计划
  const todayVisitPlans = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    return visitPlans.value.filter(plan => 
      plan.startTime.split('T')[0] === today
    )
  })

  // 计算属性：获取已完成的走访计划
  const completedVisitPlans = computed(() => {
    return visitPlans.value.filter(plan => plan.status === 'completed')
  })

  return {
    // 状态
    visitPlans,
    currentPlan,
    loading,
    total,
    
    // 方法
    fetchVisitPlans,
    fetchVisitPlanDetail,
    createVisitPlan,
    updateVisitPlan,
    batchCreateVisitPlans,
    
    // 计算属性
    todayVisitPlans,
    completedVisitPlans
  }
})